package com.atguigu.flink.chapter04;

import org.apache.flink.api.common.functions.FlatMapFunction;
import org.apache.flink.api.common.functions.MapFunction;
import org.apache.flink.api.java.functions.KeySelector;
import org.apache.flink.api.java.tuple.Tuple2;
import org.apache.flink.configuration.Configuration;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.util.Collector;

/**
 * @Author lzc
 * @Date 2023/6/16 10:07
 */
public class WcUnBounded_1 {
    public static void main(String[] args) throws Exception {
        
        Configuration conf = new Configuration();
        conf.setInteger("rest.port", 20000);
        
        
        StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment(conf);
        // 1. 获取一个流的执行环境
        //env.setParallelism(2);
        // 2. 通过执行环境,从 source 读取数据,到一个流
        env
            .socketTextStream("hadoop162", 8888)
            .flatMap(new FlatMapFunction<String, String>() {
                @Override
                public void flatMap(String line, // 读取到每行数据
                                    Collector<String> out) throws Exception {
                    String[] words = line.split(" ");  // hello world
                
                    for (String word : words) {
                        out.collect(word);
                    
                    }
                }
            })
            .map(new MapFunction<String, Tuple2<String, Long>>() {
                @Override
                public Tuple2<String, Long> map(String word) throws Exception {
                    return Tuple2.of(word, 1L);
                }
            
            })
            .filter(x -> true)
            .keyBy(new KeySelector<Tuple2<String, Long>, String>() {
                @Override
                public String getKey(Tuple2<String, Long> t) throws Exception {
                    return t.f0;
                }
            })
            .sum(1).setParallelism(4)
            .print();
        
        // 4. 启动流的执行环境
        env.execute();
    }
}
/*
 
 
 */